'use strict';

let fs  = require("fs");
let path = require("path");
let router = require("koa-router")();

function seachdir(){
    let files = fs.readdirSync(__dirname);

    let filepath = files.filter(name=>{
        return name.endsWith(".js") && name!=="index.js";
    })
    
    return filepath;
}

function register(files){
    files.forEach(item => {
        let fullpath = path.join(__dirname,item);
        
        let show = require(fullpath);
        
        for(let x in show){
            let valueArr = show[x];
            let type = valueArr[0];
            // let fn = valueArr[1];
            if(type==="get"){
                if(valueArr.length===2){
                    let fn = valueArr[1];
                    router.get(x,fn);
                }else{
                    let auth = valueArr[1];
                    let fn =valueArr[2];
                    router.get(x,auth,fn)
                }
            }else if(type==="post"){
                if(valueArr.length===2){
                    let fn = valueArr[1];
                    router.post(x,fn);
                }else{
                    let auth = valueArr[1];
                    let fn =valueArr[2];
                    router.post(x,auth,fn)
                }
            }else if(type==="put"){
                if(valueArr.length===2){
                    let fn = valueArr[1];
                    router.put(x,fn);
                }else{
                    let auth = valueArr[1];
                    let fn =valueArr[2];
                    router.put(x,auth,fn)
                }
            }else if(type==="delete"){
                if(valueArr.length===2){
                    let fn = valueArr[1];
                    router.delete(x,fn);
                }else{
                    let auth = valueArr[1];
                    let fn =valueArr[2];
                    router.delete(x,auth,fn)
                }
            }else{
                console.log("请求类型有误，请重试！！！");
            }
        }
    });
}

module.exports = function(){
    let file = seachdir();
    
    register(file);
    return router.routes();
}